package com.qinghua.blog.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class LogAspect {

    //获取日志对象
    Logger logger=LoggerFactory.getLogger(this.getClass());

    //给所有的controller添加切面把切面命名为log
    @Pointcut("execution(* com.qinghua.blog.controller.*.*(..))")
    public void log(){

    }
    //在切面前执行
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){

        ServletRequestAttributes attributes=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        String url=request.getRequestURL().toString();
        String ip=request.getRemoteAddr();

        String classMethod = joinPoint.getSignature().getDeclaringTypeName()+" "+joinPoint.getSignature().getName();
        Object[] args= joinPoint.getArgs();

        //在方法执行前获取到请求该方法的url,ip,方法名和参数
        RequestLog requestLog=new RequestLog(url,ip,classMethod,args);

        //并且记录到日志中
        logger.info("Request:{}",requestLog);
    }

    @After("log()")
    public void deAfter(){
        logger.info("-------after---------");
    }
    @AfterReturning(returning ="result",pointcut = "log()")
    public void doAfterRuturn(Object result){
        logger.info("Result:{}"+result);
    }

    public class RequestLog{
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getIp() {
            return ip;
        }

        public void setIp(String ip) {
            this.ip = ip;
        }

        public String getClassMethod() {
            return classMethod;
        }

        public void setClassMethod(String classMethod) {
            this.classMethod = classMethod;
        }

        public Object[] getArgs() {
            return args;
        }

        public void setArgs(Object[] args) {
            this.args = args;
        }

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }
        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}
